﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Text;


using MvcContrib.ControllerFactories;
using MvcContrib.Services;
using MvcContrib.Spring;
using Spring.Context.Support;

using Spring.Objects.Factory;
using Spring.Threading;
using DirectCenter.DTO;

using DirectCenter.Controllers;

namespace DirectCenter.Web
{
    // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明，
    // 请访问 http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // 路由名称
                "{controller}.mvc/{action}/{id}", // 带有参数的 URL
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值
            );

        }

        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
            //log4net配置信息
            log4net.Config.XmlConfigurator.Configure();//.DOMConfigurator.Configure();


            ModelBinders.Binders[typeof(UserDTO)] = new JsonBinder<UserDTO>();
        }
        public override void Init()
        {
            base.Init();
            ConfigureIoC();
        }

        private void ConfigureIoC()
        {
            var webApplicationContext =
                ContextRegistry.GetContext() as WebApplicationContext;
            DependencyResolver.InitializeWith(
                new SpringDependencyResolver(webApplicationContext.ObjectFactory));
            Type t = typeof(IoCControllerFactory);
            ControllerBuilder.Current.SetControllerFactory(t);

           
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            log4net.ILog logger = log4net.LogManager.GetLogger("Logger");

            if (Server.GetLastError() != null)
            {
                Exception ex = Server.GetLastError().GetBaseException();
                StringBuilder sb = new StringBuilder();
                sb.Append(ex.Message);
                sb.Append("\r\nSOURCE: " + ex.Source);
                sb.Append("\r\nFORM: " + Request.Form.ToString());
                sb.Append("\r\nQUERYSTRING: " + Request.QueryString.ToString());
                sb.Append("\r\n引发当前异常的原因: " + ex.TargetSite);
                sb.Append("\r\n堆栈跟踪: " + ex.StackTrace);
                logger.Error(sb.ToString());
                Server.ClearError();
            }
        }

    }
}